<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主机地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入主机地址"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="主机名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入主机名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="在线状态" prop="agentOnlineStatus">
        <el-select v-model="queryParams.agentOnlineStatus" placeholder="请选择状态"  clearable style="width: 160px;">
          <el-option v-for="(item, index) in service_status" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>



    <el-table v-loading="loading" :data="hostList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- 主机信息列 -->
      <el-table-column label="主机信息"  align="left">
        <template #default="scope">
          <div class="host-info">
            <div class="host-name">
              <span class="label">主机名称：</span>
              <span class="value">{{ scope.row.name || '未知' }}</span>
            </div>
            <div class="host-address">
              <span class="label">主机地址：</span>
              <span class="value">{{ scope.row.address || '未知' }}</span>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 设备状态列 -->
      <el-table-column label="设备状态" align="center">
        <template #default="scope">
          <div class="status-container">
            <el-icon class="status-icon" :class="getStatusClass(scope.row.agentOnlineStatus)">
              <Check v-if="scope.row.agentOnlineStatus === '0'" />
              <Close v-else />
            </el-icon>
            <span :class="getStatusClass(scope.row.agentOnlineStatus)">
              {{ scope.row.agentOnlineStatus === '0' ? '在线' : '离线' }}
            </span>
          </div>
        </template>
      </el-table-column>

     <!-- CPU使用率 -->
      <el-table-column label="CPU"  align="center">
        <template #default="scope">
          <div class="progress-column" v-if="scope.row.agentOnlineStatus === '0'" style="width: 100%;">
            <div class="progress-value">{{ formatPercentage(scope.row.cpuUsage) }}</div>
            <el-progress 
              :percentage="Number(scope.row.cpuUsage) || 0" 
              :color="getProgressColor(scope.row.cpuUsage)"
              :show-text="false"
              :stroke-width="8"
              style="width: 100%;"
            />
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>

      <!-- 内存使用率 -->
      <el-table-column label="内存"  align="center">
        <template #default="scope">
          <div class="progress-column" v-if="scope.row.agentOnlineStatus === '0'" style="width: 100%;">
            <div class="progress-value">{{ formatPercentage(scope.row.memoryUsage) }}</div>
            <el-progress 
              :percentage="Number(scope.row.memoryUsage) || 0" 
              :color="getProgressColor(scope.row.memoryUsage)"
              :show-text="false"
              :stroke-width="8"
              style="width: 100%;"
            />
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>

       <!-- 磁盘使用率 -->
      <el-table-column label="磁盘" align="center">
        <template #default="scope">
          <div class="progress-column" v-if="scope.row.agentOnlineStatus === '0'" style="width: 100%;">
            <div class="progress-value">
              {{ formatPercentage(getDiskAvgUsage(scope.row.diskJson)) }}
            </div>
            <el-progress
              :percentage="getDiskAvgUsage(scope.row.diskJson)"
              :color="getProgressColor(getDiskAvgUsage(scope.row.diskJson))"
              :show-text="false"
              :stroke-width="8"
              style="width: 100%;"
            />
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>

      <!-- 网络状态 -->
      <el-table-column label="网络" align="center">
        <template #default="scope">
          <div class="network-info" v-if="scope.row.agentOnlineStatus === '0'">
            <div class="network-item">
              <el-icon class="network-icon up"><Top /></el-icon>
              <span class="network-rate">{{ formatNetworkRate(scope.row.networkSentRate) }}</span>
            </div>
            <div class="network-item">
              <el-icon class="network-icon down"><Bottom /></el-icon>
              <span class="network-rate">{{ formatNetworkRate(scope.row.networkRecvRate) }}</span>
            </div>
          </div>
          <div v-else>-</div>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="View" 
            @click="handleDetail(scope.row)" 
            v-hasPermi="['monitor:host:view']"
            :disabled="scope.row.agentOnlineStatus !== '0'"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script setup name="Host">
import { listHost } from "@/api/monitor/host"
import { Check, Close, Top, Bottom } from '@element-plus/icons-vue'
import { optionProps } from "element-plus/es/components/select/src/option.mjs"
const router = useRouter()
const { proxy } = getCurrentInstance()
const { os_type,arch_type,host_type,service_status } = proxy.useDict("os_type","arch_type","host_type","service_status")
const hostList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    address: null,
    name: null,
    agentOnlineStatus: null
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询监控主机列表 */
function getList() {
  loading.value = true
  listHost(queryParams.value).then(response => {
    hostList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 状态样式
const getStatusClass = (status) => {
  return status === '0' ? 'status-online' : 'status-offline'
}

// 进度条颜色
const getProgressColor = (percentage) => {
  const value = parseFloat(percentage) || 0
  if (value < 50) {
    return '#67C23A'
  } else if (value < 80) {
    return '#E6A23C'
  } else {
    return '#F56C6C'
  }
}

// 格式化百分比
const formatPercentage = (value) => {
  const num = parseFloat(value) || 0
  return `${num.toFixed(2)}%`
}

// 格式化网络速率
const formatNetworkRate = (rate) => {
  if (!rate) return '0.00 kb/s'
    return `${rate.toFixed(2)} kb/s`

}

function getDiskAvgUsage(diskJson) {
  if (!diskJson) return 0
  let arr = []
  try {
    arr = JSON.parse(diskJson)
  } catch {
    return 0
  }
  if (!Array.isArray(arr) || arr.length === 0) return 0
  const total = arr.reduce((sum, disk) => sum + (parseFloat(disk.usage) || 0), 0)
  return arr.length ? +(total / arr.length).toFixed(2) : 0
}

// 安装探针
const handleInstall = (row) => {
  // 安装探针的逻辑
  proxy.$modal.confirm('确认安装探针到主机 "' + row.name + '" 吗？').then(() => {
    // 调用安装API
    proxy.$modal.msgSuccess("安装命令已发送")
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    address: null,
    name: null,
    agentOnlineStatus: null
  }
  proxy.resetForm("hostRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 查看详情 - 跳转到详情页
const handleDetail = (row) => {
  const hostId = row.hostId 
  router.push(`/monitor/host-detail/`+hostId)
}

getList()
</script>

<style scoped>
.host-info {
  line-height: 1.6;
}

.host-name,
.host-address {
  display: flex;
}

.label {
  color: #909399;
  min-width: 70px;
  text-align: right;
}

.value {
  color: #303133;
  flex: 1;
}

.status-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.status-icon {
  font-size: 16px;
}

.status-online {
  color: #67C23A;
}

.status-offline {
  color: #F56C6C;
}

.progress-column {
  display: flex;
  flex-direction: column;
  gap: 6px;
  align-items: center;
}

.progress-value {
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.network-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.network-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.network-icon {
  font-size: 12px;
}

.network-icon.up {
  color: #F56C6C;
}

.network-icon.down {
  color: #67C23A;
}

.network-rate {
  font-size: 12px;
  color: #606266;
}

:deep(.el-progress-bar) {
  padding-right: 0;
  margin-right: 0;
}

:deep(.el-progress-bar__inner) {
  transition: all 0.3s ease;
}
</style>